//
//  KFDAccountManager.m
//  KFD
//
//  Created by JIRENTIANXIANG on 6/8/15.
//  Copyright (c) 2015 KFD. All rights reserved.
//

#import "KFDAccountManager.h"
#import "KFDSettingsManager.h"
#import "NSMutableDictionary+checkForNil.h"
#import "GeTuiSdk.h"
#import "AppDelegate.h"
#import "JTToast.h"

@interface KFDAccountManager ()

@property (assign,atomic,getter=isLogin) BOOL login;
@property (assign,atomic,getter=isVIP) BOOL VIP;
@property (assign,atomic,getter=isVIPQualified) BOOL VIPQualified;

@property (atomic,copy) NSString* nickname;
@property (atomic,copy) NSString* realName;
@property (atomic,copy) NSString* gender;
@property (atomic,copy) NSString* phoneNumber;
@property (atomic,copy) NSString* emailAddress;
@property (atomic,copy) NSString* avatar;

@property (atomic,strong) NSHTTPCookie* financialServiceCookie;
@property (atomic,copy) NSString* injectionUrl;
@property (atomic,copy) NSString* withdrawUrl;

@end

@implementation KFDAccountManager

//-------------------------------------------------------------------------
// test
//-------------------------------------------------------------------------
//-(BOOL)isVIP
//{
//    return YES;
//}
//-------------------------------------------------------------------------

+(KFDAccountManager*)sharedManager
{
    static KFDAccountManager* _manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager=[[KFDAccountManager alloc] init];
    });
    return _manager;
}

-(instancetype)init
{
    if (self=[super init]) {
        self.login=NO;
        self.VIP=NO;
    }
    return self;
}

-(NSURLSessionTask*)getCheckcodeForRegistrationWithPhoneNumber:(NSString *)phoneNumber successHandler:(KFDGetCheckcodeSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client getCheckcodeWithType:@"register" phoneNumber:phoneNumber successHandler:successHandler failureHandler:failureHandler];
}

-(NSURLSessionTask*)getCheckcodeForChangingPasswordWithPhoneNumber:(NSString*)phoneNumber successHandler:(KFDGetCheckcodeSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client getCheckcodeWithType:@"password" phoneNumber:phoneNumber successHandler:successHandler failureHandler:failureHandler];
}

-(NSURLSessionTask*)registerWithPhoneNubmer:(NSString *)phoneNumber realName:(NSString *)realName checkcode:(NSString *)checkcode successHandler:(KFDRegisterSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client registerWithPhoneNubmer:phoneNumber realName:realName checkcode:checkcode successHandler:^{
        self.login=YES;
        self.phoneNumber=phoneNumber;
        self.realName=realName;
        if (successHandler) {
            successHandler();
        }
    } failureHandler:failureHandler];
}

-(void)loginLastSession
{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    NSString* phoneNumber=[defaults objectForKey:@"phoneNumber"];
    NSString* password=[defaults objectForKey:@"password"];
    if (phoneNumber&&password) {
        [self loginWithPhoneNumber:phoneNumber password:password successHandler:^{
            
        } failureHandler:^(KFDResponseBody *response) {
            
        }];
    }
}

-(NSURLSessionTask*)loginWithPhoneNumber:(NSString *)phoneNumber password:(NSString *)password successHandler:(KFDLoginSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client loginWithPhoneNumber:phoneNumber password:password successHandler:^{
        self.login=YES;
        self.phoneNumber=phoneNumber;
        NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        [defaults setObject:phoneNumber forKey:@"phoneNumber"];
        [defaults setObject:password forKey:@"password"];
        
        [client getAccountInfoWithSuccessHandler:^(KFDAccountInfo *accountInfo) {
            self.nickname=accountInfo.nickname;
            self.realName=accountInfo.realname;
            self.gender=[accountInfo.sex isEqualToString:@"1"]?@"男":@"女";
            self.avatar=accountInfo.face;
            [[NSNotificationCenter defaultCenter] postNotificationName:KFDAccountInfoReadyNotificatoin object:nil];
        } failureHandler:^(KFDResponseBody *response) {
            
        }];
        [client getVIPInfoWithSuccessHandler:^(BOOL isVIP, BOOL isVIPQualified) {
            self.VIP=isVIP;
            self.VIPQualified=isVIPQualified;
        } failureHandler:^(KFDResponseBody *response) {
            
        }];
//        KFDSettingsManager* settingsManager=[KFDSettingsManager sharedManager];
//        [settingsManager loadSettingsForCurrentAccount];
        
        [client getFinancialServiceInterfaceWithSuccessHandler:^(NSString *withdraw, NSString *injection) {
            self.injectionUrl=injection;
            self.withdrawUrl=[withdraw stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            if (injection.length==0) {
                self.injectionUrl=nil;
            }
            if (withdraw.length==0) {
                self.withdrawUrl=nil;
            }
            [client getFinancialServiceCookieWithSuccessHandler:^(NSString *name, NSString *value) {
                NSMutableDictionary* properties=[NSMutableDictionary dictionary];
                [properties setNotNilObject:name forKey:NSHTTPCookieName];
                [properties setNotNilObject:value forKey:NSHTTPCookieValue];
                [properties setNotNilObject:@"/" forKey:NSHTTPCookiePath];
                [properties setNotNilObject:[NSURL URLWithString:injection].host forKey:NSHTTPCookieDomain];
                self.financialServiceCookie=[NSHTTPCookie cookieWithProperties:properties];
            } failureHandler:^(KFDResponseBody *response) {
                
            }];
        } failureHandler:^(KFDResponseBody *response) {
            
        }];
        
        AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
        [client updateAccountInfoWithNickname:nil province:nil city:nil avatar:nil gender:nil clientId:[GeTuiSdk clientId] pushToken:appDelegate.deviceToken successHandler:^{
        } failureHandler:^(KFDResponseBody *response) {
            
        }];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:KFDLoginSuccessNotification object:nil];
        
        if (successHandler) {
            successHandler();
        }
    } failureHandler:failureHandler];
}

-(NSURLSessionTask*)setNickname:(NSString *)nickname password:(NSString *)password successHandler:(KFDSetNicknameAndPasswordSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client setNickname:nickname password:password successHandler:^{
        self.nickname=nickname;
        if (successHandler) {
            successHandler();
        }
    } failureHandler:failureHandler];
}

-(NSURLSessionTask*)updateNickname:(NSString *)nickname successHandler:(KFDUpdateAccountInfoSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client updateAccountInfoWithNickname:nickname province:nil city:nil avatar:nil gender:nil clientId:nil pushToken:nil successHandler:^{
        self.nickname=nickname;
        if (successHandler) {
            successHandler();
        }
    } failureHandler:failureHandler];
}

-(NSURLSessionTask*)updatePassword:(NSString *)password token:token successHandler:(KFDUpdateAccountInfoSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client setPassword:password token:token successHandler:successHandler failureHandler:failureHandler];
}

-(NSURLSessionTask*)bindEmail:(NSString *)email successHandler:(KFDBindEmailSuccessHandler)successHandler failulreHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client bindEmail:email successHandler:^{
        self.emailAddress=email;
        if (successHandler) {
            successHandler(email);
        }
    } failulreHandler:failureHandler];
}

-(NSURLSessionTask*)getInjectionInterfaceWithSuccessHandler:(KFDGetInjectionInterfaceSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client getFinancialServiceInterfaceWithSuccessHandler:^(NSString *withdraw, NSString *injection) {
        if (successHandler) {
            successHandler(injection);
        }
    } failureHandler:failureHandler];
}

-(NSURLSessionTask*)getWithdrawInterfaceWithSuccessHandler:(KFDGetWithdrawInterfaceSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client getFinancialServiceInterfaceWithSuccessHandler:^(NSString *withdraw, NSString *injection) {
        if (successHandler) {
            successHandler(withdraw);
        }
    } failureHandler:failureHandler];
}

-(NSURLSessionTask*)applyForVIPWithSuccessHandler:(KFDApplyForVIPSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client applyForVIPWithSuccessHandler:^{
        self.VIP=YES;
        if (successHandler) {
            successHandler();
        }
    } failureHandler:failureHandler];
}

-(NSURLSessionTask*)setBankAccountInfo:(KFDBankAccountInfo*)bankInfo successHandler:(KFDSetBankSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client setBankAccountInfo:bankInfo successHandler:successHandler failureHandler:failureHandler];
}

-(NSURLSessionTask*)verifyCheckcode:(NSString *)checkcode withType:(NSString *)type phoneNumber:(NSString *)phoneNumber successHandler:(KFDVerifyCheckcodeSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client verifyCheckcode:checkcode withType:type phoneNumber:phoneNumber successHandler:successHandler failureHandler:failureHandler];
}

-(void)logout
{
    self.login=NO;
    NSUserDefaults* defaullts=[NSUserDefaults standardUserDefaults];
    [defaullts removeObjectForKey:@"phoneNumber"];
    [defaullts removeObjectForKey:@"password"];
    NSHTTPCookieStorage* storage=[NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray* cookies=storage.cookies;
    for (NSHTTPCookie* cookie in cookies) {
        if ([cookie.name isEqualToString:@"__TOKEN"]) {
            [storage deleteCookie:cookie];
        }
    }
    self.injectionUrl=nil;
    self.withdrawUrl=nil;
    self.avatar=nil;
    self.nickname=nil;
}

-(void)saveUserAddress:(KFDUserAddress *)address
{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    [defaults setValue:address.province forKey:@"province"];
    [defaults setValue:address.city forKey:@"city"];
    [defaults setValue:address.district forKey:@"district"];
}

-(KFDUserAddress*)userAddress
{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    KFDUserAddress* userAddress=[[KFDUserAddress alloc] init];
    userAddress.province=[defaults stringForKey:@"province"];
    userAddress.city=[defaults stringForKey:@"city"];
    userAddress.district=[defaults stringForKey:@"district"];
    return userAddress;
}

-(NSURLSessionTask*)getFinancialServiceCookieWithSuccessHandler:(KFDGetFinancialServiceCookieSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client getFinancialServiceCookieWithSuccessHandler:successHandler failureHandler:failureHandler];
}

-(NSURLSessionTask*)updateAvatar:(NSString *)url successHandler:(KFDUpdateAccountInfoSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    KFDClient* client=[KFDClient sharedClient];
    return [client updateAccountInfoWithNickname:nil province:nil city:nil avatar:url gender:nil clientId:nil pushToken:nil successHandler:^{
        self.avatar=url;
        if (successHandler) {
            successHandler();
        }
    } failureHandler:failureHandler];
}

@end

//------------------------------------------------------------------------

#define PHONE_NUMBER_LIMIT 11
#define CHECKCODE_LIMIT 6

@implementation KFDAccountManager(BusinessRules)

-(BOOL)phoneNumberLengthExceedLimit:(NSInteger)length
{
    return length>PHONE_NUMBER_LIMIT;
}

-(BOOL)checkcodeLengthExceedLimit:(NSInteger)length
{
    return length>CHECKCODE_LIMIT;
}

-(BOOL)checkRealName:(NSString *)realName illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (realName&&realName.length>0) {
        return true;
    }else if(handler){
        handler(@"请输入您的真实姓名");
    }
    return NO;
}

-(BOOL)checkPhoneNumber:(NSString *)phoneNumber illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (phoneNumber&&phoneNumber.length>0) {
        if (phoneNumber.length==11) {
            return YES;
        }else if(handler){
            handler(@"手机号码格式有误");
        }
    }else if(handler){
        handler(@"请输入手机号码");
    }
    return NO;
}

-(BOOL)checkCheckcode:(NSString *)checkcode illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (checkcode&&checkcode.length>0) {
        return YES;
    }else if(handler){
        handler(@"请输入验证码");
    }
    return NO;
}

-(BOOL)checkNickname:(NSString *)nickname illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (nickname&&nickname.length>0) {
        return YES;
    }else if(handler){
        handler(@"请输入昵称");
    }
    return NO;
}

-(BOOL)checkPassword:(NSString *)password illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (password&&password.length>0) {
        return YES;
    }else if(handler){
        handler(@"请输入密码");
    }
    return NO;
}

-(BOOL)checkEmail:(NSString *)email illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (email&&email.length>0) {
        return YES;
    }else{
        handler(@"请输入邮箱地址");
    }
    return NO;
}

-(BOOL)checkUserAddress:(KFDUserAddress *)userAddress illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (!userAddress.province) {
        if (handler) {
            handler(@"请填写省份");
        }
        return NO;
    }
    if (!userAddress.city){
        if (handler) {
            handler(@"请填写城市");
        }
        return NO;
    }
    if (!userAddress.district){
        if (handler) {
            handler(@"请填写区");
        }
        return NO;
    }
    return YES;
}

-(BOOL)checkBankAccountInfo:(KFDBankAccountInfo *)bankAccountInfo illegalInputHandler:(KFDAccountManagerIllegalInputHandler)handler
{
    if (!bankAccountInfo.bank_name||bankAccountInfo.account.length==0) {
        handler(@"请填写您的银行账号");
        return NO;
    }
    if (!bankAccountInfo.account||bankAccountInfo.bank_name.length==0) {
        handler(@"请选择银行");
        return NO;
    }
    if (!bankAccountInfo.branch||bankAccountInfo.branch.length==0) {
        handler(@"请填写支行名称");
    }
    return YES;
}

@end
